package org.ielts.action.security;

import org.ielts.action.BaseAction;
import org.ielts.domain.security.Role;
import org.ielts.service.security.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Transactional;
import com.yifeng.modules.annotations.Module;
import com.yifeng.modules.annotations.Operation;
import com.yifeng.struts2.action.FormAction;
import com.yifeng.utils.JsonResultBuilder;

import static com.yifeng.struts2.RequestParameters.*;
import static com.yifeng.struts2.ResultParameters.*;
import static com.yifeng.struts2.ResultConstants.*;
import static com.yifeng.struts2.ActionUtils.*;

@Module(namespaceName = "security")
public class RoleAction extends BaseAction {

	@Autowired
	RoleService roleService;

	@Operation(result = FILL)
	public String listRole() {

		Iterable<Role> roles = roleService.listAllRole();

		put("roles", roles);
		return FILL;
	}

	@Operation(result = FILL)
	public String createRole() {

		return FILL;
	}

	@Operation(result = JSON)
	public String doCreateRole() {
		String name = form.readString("name");
		String title = form.readString("title");

		Role role = roleService.findByName(name);
		if (role != null) {
			setJson(JsonResultBuilder.success(false).msg("已存在同名的角色。").json());
		} else {
			roleService.createRole(name, title);
			setJson(JsonResultBuilder.success(true).msg("创建角色成功。").json());
		}

		return JSON;
	}

	@Operation(result = JSON)
	public String doRemoveRole() {
		String id = form.readString("id");

		// TODO 关联关系删除
		roleService.removeRole(id);
		setJson(JsonResultBuilder.success(true).msg("删除角色成功。").json());

		return JSON;
	}

	@Operation(result = FILL)
	public String modifyRole() {
		String id = form.readString("id");

		Role role = roleService.findRole(id);

		put("role", role);

		return FILL;
	}

	@Operation(result = JSON)
	public String doModifyRole() {
		String id = form.readString("id");
		String name = form.readString("name");
		String title = form.readString("title");

		Role existsRole = roleService.findByName(name);

		if (existsRole != null && !existsRole.getId().equals(id)) {
			setJson(JsonResultBuilder.success(false).msg("已存在同名的角色。").json());
		} else {
			roleService.modifyRole(id, name, title);
			setJson(JsonResultBuilder.success(true).msg("修改角色成功。").json());
		}

		return JSON;
	}

}
